package com.bw.a2207a.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.a2207a.base.BaseBean
import com.bw.a2207a.base.BaseViewModel
import com.bw.a2207a.bean.BannerBean
import com.bw.a2207a.bean.GoodsBean
import com.bw.a2207a.db.CartDbUtil
import com.bw.a2207a.bean.SearchHistoryBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.io.File

/**
 *
 * @ClassName: HomeViewModel
 * @Description: java类作用描述
 * @Author: zhangyanchao
 * @CreateDate: 2024/10/23 12:08 PM
 * @Version: 1.0
 */
class HomeViewModel : BaseViewModel() {

    val goodsAddLiveData = MutableLiveData<BaseBean<String>>()
    val bannerLiveData = MutableLiveData<BaseBean<List<BannerBean>>>()
    val goodsLiveData = MutableLiveData<BaseBean<List<GoodsBean>>>()
    val searchLiveData = MutableLiveData<List<SearchHistoryBean>>()
    //获取banner 列表
    fun getBanners(){
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                //同步
                val da = apiService.getBanner()
                bannerLiveData.postValue(da)
            }
        }
    }

    //获取首页商品列表
    fun getGoods(id:Int,page:Int,size:Int){
        viewModelScope.launch(Dispatchers.IO) {
            goodsLiveData.postValue(apiService.getGoods(id,page,size))
        }
    }


    //商品详情 -添加购物车
    fun addCar(id: Int) {
        val map = HashMap<String, Int>()
        map["count"] = 1//商品个数
        map["goods_id"] = id
        viewModelScope.launch(Dispatchers.IO) {
            goodsAddLiveData.postValue(apiService.addCar(map))
        }
    }
    //从本地数据库查询历史记录
    fun searchHistory(){
        viewModelScope.launch(Dispatchers.IO) {
            //查询数据库，获取搜索历史
            val querySearchs = CartDbUtil.cartDb.getSearchDao().querySearchs()
            searchLiveData.postValue(querySearchs)
        }
    }

    fun uploadFile(){
        viewModelScope.launch {
            val parameterMap = mutableMapOf<String, Any>()
            val stringValue = "This is title"
            parameterMap["title"] = stringValue
            val file = File("path/to/your/file.jpg")
            val fileRequestBody = RequestBody.create("image/jpeg".toMediaTypeOrNull(), file)
            parameterMap["media"] = fileRequestBody
            apiService.uploadData("http://mobile.bwstudent.com/hotNews/shoot/verify/v1/publishShoot",parameterMap)
        }
    }

}